from flask import Blueprint, request, jsonify
from db import db1
from math import ceil
import json

bp_fenlei = Blueprint('lianxi', __name__)


# 添加分类
@bp_fenlei.route('/add', methods=['POST'])
def addcate():
    data = request.data
    if data:
        data = json.loads(data)
    else:
        data = request.form
    sql = """insert into cate(name) values('%s')""" % (data['name'])
    db1.insert(sql)
    return jsonify({'code': 200})


# 添加商品
@bp_fenlei.route('/addgoods', methods=['POST','GET'])
def addgoods():
    data = request.data
    if data:
        data = json.loads(data)
    else:
        data = request.form
    if request.method == 'POST':
        sql = """insert into goods values(0,'%s','%d')""" % (data['name'], int(data['cid']))
        db1.insert(sql)
        return jsonify({'code': 200})
    elif request.method == 'GET':
        cpage = int(request.args.get('cpage'))
        size = 2
        start = (cpage - 1) * size
        sql = """select g.id,g.name,g.cid,c.name from goods as g left join cate as c on g.cid=c.id order by id desc limit %d,%d""" % (
        start, size)
        list = db1.findall(sql)
        sql = """select count(-1) as co  from goods"""
        numm = db1.findall(sql)
        total = ceil(numm[0]['co']/size)
        return jsonify({'code': 200,"list":list,"numm":total})

@bp_fenlei.route('/wenzhang')
def wenzhang():
    sql = """select * from article"""
    list = db1.findall(sql)
    return jsonify({'code':200,"list":list})

@bp_fenlei.route('/denlu',methods=['POST','GET'])
def denlu():
    if request.method == 'POST':
        data = request.data
        if data:
            data = json.loads(data)
        else:
            data = request.form
        sql =  """select * from user"""
        list = db1.findall(sql)
        if data['username'] == list[0]['username']:
            if data['password'] == list[0]['password']:
                return jsonify({"code":200,"mes":"登录成功","userid":list[0]['id']})
            else:
                return jsonify({'code': 200, "mes": "密码错误"})
        else:
            return jsonify({'code':200,"mes":"没有次用户"})

@bp_fenlei.route('/tlacks',methods=['POST','GET'])
def tlacks():
    if request.method=='POST':
        data = request.data
        if data:
            data = json.loads(data)
        else:
            data = request.form
        sql = "insert into comment values(%d,'%s',%d,%d)"%(0,data["frm"]['tlack'],int(data["tid"]),int(data["uid"]))
        db1.insert(sql)
        return jsonify({'code': 200})
    elif request.method=='GET':
        tid = request.args.get('tid')
        sql = """select * from comment where tid=%d"""%int(tid)
        aaa = db1.findall(sql)
        return jsonify({'code': 200, "list": aaa})












